{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ['CUDA_VISIBLE_DEVICES'] = '0'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "import json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('dataset-bpe.json') as fopen:\n",
    "    data = json.load(fopen)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_X = data['train_X']\n",
    "train_Y = data['train_Y']\n",
    "test_X = data['test_X']\n",
    "test_Y = data['test_Y']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "EOS = 2\n",
    "GO = 1\n",
    "vocab_size = 32000"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_Y = [i + [2] for i in train_Y]\n",
    "test_Y = [i + [2] for i in test_Y]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import beam_search\n",
    "\n",
    "def pad_second_dim(x, desired_size):\n",
    "    padding = tf.tile([[[0.0]]], tf.stack([tf.shape(x)[0], desired_size - tf.shape(x)[1], tf.shape(x)[2]], 0))\n",
    "    return tf.concat([x, padding], 1)\n",
    "\n",
    "class Translator:\n",
    "    def __init__(self, size_layer, num_layers, embedded_size, learning_rate):\n",
    "        \n",
    "        def cells(reuse=False):\n",
    "            return tf.nn.rnn_cell.GRUCell(size_layer,reuse=reuse)\n",
    "        \n",
    "        self.X = tf.placeholder(tf.int32, [None, None])\n",
    "        self.Y = tf.placeholder(tf.int32, [None, None])\n",
    "        \n",
    "        self.X_seq_len = tf.count_nonzero(self.X, 1, dtype = tf.int32)\n",
    "        self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype = tf.int32)\n",
    "        batch_size = tf.shape(self.X)[0]\n",
    "        \n",
    "        embeddings = tf.Variable(tf.random_uniform([vocab_size, embedded_size], -1, 1))\n",
    "        \n",
    "        def forward(x, y, reuse = False):\n",
    "            X_seq_len = tf.count_nonzero(x, 1, dtype = tf.int32)\n",
    "            Y_seq_len = tf.count_nonzero(y, 1, dtype = tf.int32)\n",
    "            with tf.variable_scope('model',reuse=reuse):\n",
    "                encoder_embedded = tf.nn.embedding_lookup(embeddings, x)\n",
    "                decoder_embedded = tf.nn.embedding_lookup(embeddings, y)\n",
    "                rnn_cells = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)])\n",
    "                _, last_state = tf.nn.dynamic_rnn(rnn_cells, encoder_embedded,\n",
    "                                                  sequence_length=X_seq_len,\n",
    "                                                  dtype = tf.float32)\n",
    "                \n",
    "            with tf.variable_scope(\"decoder\",reuse=reuse):\n",
    "                rnn_cells_dec = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)])\n",
    "                outputs, _ = tf.nn.dynamic_rnn(rnn_cells_dec, decoder_embedded, \n",
    "                                               sequence_length=Y_seq_len,\n",
    "                                               initial_state = last_state,\n",
    "                                               dtype = tf.float32)\n",
    "                return tf.layers.dense(outputs,vocab_size)\n",
    "            \n",
    "        main = tf.strided_slice(self.X, [0, 0], [batch_size, -1], [1, 1])\n",
    "        decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n",
    "        self.training_logits = forward(self.X, decoder_input, reuse = False)\n",
    "        \n",
    "        self.training_logits = self.training_logits[:, :tf.reduce_max(self.Y_seq_len)]\n",
    "        self.training_logits = pad_second_dim(self.training_logits, tf.reduce_max(self.Y_seq_len))\n",
    "            \n",
    "        masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n",
    "        self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n",
    "                                                     targets = self.Y,\n",
    "                                                     weights = masks)\n",
    "        self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n",
    "        y_t = tf.argmax(self.training_logits,axis=2)\n",
    "        y_t = tf.cast(y_t, tf.int32)\n",
    "        self.prediction = tf.boolean_mask(y_t, masks)\n",
    "        mask_label = tf.boolean_mask(self.Y, masks)\n",
    "        correct_pred = tf.equal(self.prediction, mask_label)\n",
    "        correct_index = tf.cast(correct_pred, tf.float32)\n",
    "        self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))\n",
    "        \n",
    "        initial_ids = tf.fill([batch_size], GO)\n",
    "        def symbols_to_logits(ids):\n",
    "            x = tf.contrib.seq2seq.tile_batch(self.X, 1)\n",
    "            logits = forward(x, ids, reuse = True)\n",
    "            return logits[:, tf.shape(ids)[1]-1, :]\n",
    "        \n",
    "        final_ids, final_probs, _ = beam_search.beam_search(\n",
    "            symbols_to_logits,\n",
    "            initial_ids,\n",
    "            1,\n",
    "            tf.reduce_max(self.X_seq_len),\n",
    "            vocab_size,\n",
    "            0.0,\n",
    "            eos_id = EOS)\n",
    "        \n",
    "        self.fast_result = final_ids"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "size_layer = 512\n",
    "num_layers = 2\n",
    "embedded_size = 256\n",
    "learning_rate = 1e-3\n",
    "batch_size = 128\n",
    "epoch = 20"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/util/deprecation.py:507: calling count_nonzero (from tensorflow.python.ops.math_ops) with axis is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "reduction_indices is deprecated, use axis instead\n",
      "WARNING:tensorflow:From <ipython-input-7-dfcae152f57e>:11: GRUCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.GRUCell, and will be replaced by that in Tensorflow 2.0.\n",
      "WARNING:tensorflow:From <ipython-input-7-dfcae152f57e>:28: MultiRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.StackedRNNCells, and will be replaced by that in Tensorflow 2.0.\n",
      "WARNING:tensorflow:From <ipython-input-7-dfcae152f57e>:31: dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `keras.layers.RNN(cell)`, which is equivalent to this API\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:559: Layer.add_variable (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `layer.add_weight` method instead.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:565: calling Constant.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Call initializer instance with the dtype argument instead of passing it to the constructor\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:575: calling Zeros.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Call initializer instance with the dtype argument instead of passing it to the constructor\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn.py:244: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use tf.where in 2.0, which has the same broadcast rule as np.where\n",
      "WARNING:tensorflow:From <ipython-input-7-dfcae152f57e>:39: dense (from tensorflow.python.layers.core) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use keras.layers.Dense instead.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/layers/core.py:187: Layer.apply (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `layer.__call__` method instead.\n",
      "WARNING:tensorflow:\n",
      "The TensorFlow contrib module will not be included in TensorFlow 2.0.\n",
      "For more information, please see:\n",
      "  * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md\n",
      "  * https://github.com/tensorflow/addons\n",
      "  * https://github.com/tensorflow/io (for I/O related ops)\n",
      "If you depend on functionality not listed there, please file an issue.\n",
      "\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensor2tensor/utils/beam_search.py:745: to_float (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use `tf.cast` instead.\n"
     ]
    }
   ],
   "source": [
    "tf.reset_default_graph()\n",
    "sess = tf.InteractiveSession()\n",
    "model = Translator(size_layer, num_layers, embedded_size, learning_rate)\n",
    "sess.run(tf.global_variables_initializer())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "pad_sequences = tf.keras.preprocessing.sequence.pad_sequences"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[array([[[    1,  1699,  1699, 25298, 13174, 13174, 20508, 20508, 27483,\n",
       "          27483, 16300, 16300, 30602, 30602, 30602, 30602, 17594, 17594,\n",
       "          17594, 13492, 13492, 13492, 24412, 24412, 24498, 14195,  3280,\n",
       "           3280, 14195, 26668, 26668, 11589, 28701,  4993, 10499, 10499,\n",
       "          10499]],\n",
       " \n",
       "        [[    1,  4774,  4774,  4774, 12851, 26979, 20549, 20549, 20549,\n",
       "          20549, 20549, 31327, 31327,  5790,  5578,  5578, 22044, 23720,\n",
       "           6754,  6754, 13434, 18976, 18976,  9528,  9528, 15676, 15676,\n",
       "          31673, 31673, 30900, 30900, 30900,  3430,  3430,  3430, 25223,\n",
       "          25223]],\n",
       " \n",
       "        [[    1,  6792, 29592, 29592, 26695,  8311,  3801,  3801, 12131,\n",
       "          14019,  8283,  7502,  7502,  7502,  8292,  8292,  8292,  8953,\n",
       "           8953,  4081,  4081,  1219, 27847, 27478, 27478, 27478, 27478,\n",
       "           2991, 18961, 18961, 18961, 28795, 28795, 11372, 11319, 11319,\n",
       "          11319]],\n",
       " \n",
       "        [[    1, 14047, 13766, 13766, 21572, 21572, 21572,  9470, 29270,\n",
       "          29270, 29270, 29270, 29270, 29270, 29270, 29270,  8503, 12957,\n",
       "          12957, 15432, 22491, 22491, 29845, 29845, 29845, 29845, 30964,\n",
       "           2339,  2339, 23023, 23023,  4824,  4824,  4824, 27164, 27164,\n",
       "          30847]],\n",
       " \n",
       "        [[    1, 19814, 19814,  7490,  7490, 28382, 17712,  6460,  6460,\n",
       "           2601,  2601,  2601,  2601, 20538, 19267, 19267, 30283, 30283,\n",
       "          30283, 30283, 25068, 25068, 25068, 25068, 23501, 23501, 23501,\n",
       "          31300, 31300, 12276, 12276, 12276, 12276, 12276,  8503,  8503,\n",
       "           8503]],\n",
       " \n",
       "        [[    1,  7372,  2973,  2973,  2973, 10024, 23110, 23110,  3482,\n",
       "           3482,  3482, 24776, 24776, 16503, 13338, 13338, 13338, 13338,\n",
       "          13338, 13338, 28709, 28709, 22350, 22350, 22350, 17968, 13032,\n",
       "          23589, 23589,  1738,  1738,  1738,  1738, 16882, 16882,  1738,\n",
       "           4076]],\n",
       " \n",
       "        [[    1,  5171,   881,   881,   242,  4930,  4930,  4930,    30,\n",
       "             30, 14999, 14999, 14999, 24861, 24861, 24861,  7867,  7867,\n",
       "           7867,  7867, 14651, 14651, 31168, 31168, 31168, 10739, 10739,\n",
       "          10739, 10739,  1542, 30434, 20070, 16599, 16599, 16599, 16692,\n",
       "          22524]],\n",
       " \n",
       "        [[    1,  2315,  2315,  2315, 21240, 25521, 21240, 28889, 28889,\n",
       "          28889, 28889, 15486, 21715, 21715, 21715,  3580,  3580,  3580,\n",
       "           3580, 15582, 15582, 15582, 15582, 14999, 14999, 10857, 10857,\n",
       "          10857, 14999, 14999, 10857, 15432, 15432, 24015,  8530, 28617,\n",
       "          28617]],\n",
       " \n",
       "        [[    1, 12908, 26838, 26838, 20206, 20206,  1132,  6848,  6848,\n",
       "           2506,  2506, 11849, 11849, 10894, 25315, 15065, 15065, 15065,\n",
       "          25078, 25078, 25078, 21837, 21837, 15861, 30294, 15861, 24472,\n",
       "           4800,  4800, 10936, 10936, 10936, 10936,  6877,  6877,  5928,\n",
       "          21644]],\n",
       " \n",
       "        [[    1, 20857, 24836, 24836, 24836, 25389, 25389, 25389, 12705,\n",
       "          12705, 12705, 12705, 30591,  1357,  1357,  4886,  4886,  4886,\n",
       "           4886,  4886,  3972,  3972,  3972,  3972,  8270,  8270, 27491,\n",
       "          13782, 13782, 24848, 10786, 10786, 22731, 20949, 19155, 19155,\n",
       "          19155]]], dtype=int32), 10.372949, 0.0]"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "batch_x = pad_sequences(train_X[:10], padding='post')\n",
    "batch_y = pad_sequences(train_Y[:10], padding='post')\n",
    "\n",
    "sess.run([model.fast_result, model.cost, model.accuracy], \n",
    "         feed_dict = {model.X: batch_x, model.Y: batch_y})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:29<00:00,  3.48it/s, accuracy=0.116, cost=6.71] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:04<00:00,  8.35it/s, accuracy=0.118, cost=6.47]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, training avg loss 7.259059, training avg acc 0.100110\n",
      "epoch 1, testing avg loss 6.605304, testing avg acc 0.130204\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [08:16<00:00,  3.15it/s, accuracy=0.136, cost=5.84]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:04<00:00,  8.40it/s, accuracy=0.14, cost=6.02] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 2, training avg loss 6.237480, training avg acc 0.142159\n",
      "epoch 2, testing avg loss 6.063695, testing avg acc 0.147860\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:29<00:00,  3.48it/s, accuracy=0.17, cost=5.1]  \n",
      "minibatch loop: 100%|██████████| 40/40 [00:04<00:00,  8.35it/s, accuracy=0.145, cost=5.85]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 3, training avg loss 5.660863, training avg acc 0.160283\n",
      "epoch 3, testing avg loss 5.856858, testing avg acc 0.153124\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:29<00:00,  3.48it/s, accuracy=0.204, cost=4.52]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:04<00:00,  8.34it/s, accuracy=0.134, cost=5.86]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 4, training avg loss 5.244004, training avg acc 0.175927\n",
      "epoch 4, testing avg loss 5.797784, testing avg acc 0.153161\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:34<00:00,  3.44it/s, accuracy=0.241, cost=4.06]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.66it/s, accuracy=0.129, cost=5.87]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 5, training avg loss 4.916309, training avg acc 0.192438\n",
      "epoch 5, testing avg loss 5.818074, testing avg acc 0.150953\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:57<00:00,  3.27it/s, accuracy=0.283, cost=3.77]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:04<00:00,  8.59it/s, accuracy=0.113, cost=5.96]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 6, training avg loss 4.665821, training avg acc 0.208163\n",
      "epoch 6, testing avg loss 5.951388, testing avg acc 0.147641\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:27<00:00,  3.49it/s, accuracy=0.328, cost=3.49]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:04<00:00,  8.52it/s, accuracy=0.118, cost=6.02]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 7, training avg loss 4.475893, training avg acc 0.222753\n",
      "epoch 7, testing avg loss 5.988914, testing avg acc 0.148660\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:26<00:00,  3.50it/s, accuracy=0.362, cost=3.25]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:04<00:00,  8.39it/s, accuracy=0.145, cost=6.1] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 8, training avg loss 4.313465, training avg acc 0.237071\n",
      "epoch 8, testing avg loss 6.070773, testing avg acc 0.148026\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:26<00:00,  3.50it/s, accuracy=0.378, cost=3.09]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:04<00:00,  8.51it/s, accuracy=0.124, cost=6.13]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 9, training avg loss 4.178759, training avg acc 0.250469\n",
      "epoch 9, testing avg loss 6.177392, testing avg acc 0.143839\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:27<00:00,  3.49it/s, accuracy=0.415, cost=2.93]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:04<00:00,  8.45it/s, accuracy=0.118, cost=6.25]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 10, training avg loss 4.073587, training avg acc 0.261016\n",
      "epoch 10, testing avg loss 6.276986, testing avg acc 0.141884\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:27<00:00,  3.49it/s, accuracy=0.425, cost=2.87]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:04<00:00,  8.48it/s, accuracy=0.102, cost=6.37]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 11, training avg loss 3.983001, training avg acc 0.270596\n",
      "epoch 11, testing avg loss 6.356074, testing avg acc 0.139292\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:27<00:00,  3.50it/s, accuracy=0.427, cost=2.83]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:04<00:00,  8.50it/s, accuracy=0.108, cost=6.36]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 12, training avg loss 3.893450, training avg acc 0.280842\n",
      "epoch 12, testing avg loss 6.449306, testing avg acc 0.136069\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:25<00:00,  3.51it/s, accuracy=0.448, cost=2.69]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:04<00:00,  8.34it/s, accuracy=0.108, cost=6.41]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 13, training avg loss 3.812129, training avg acc 0.290391\n",
      "epoch 13, testing avg loss 6.537201, testing avg acc 0.133593\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:43<00:00,  3.37it/s, accuracy=0.455, cost=2.66]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:04<00:00,  8.32it/s, accuracy=0.118, cost=6.46]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 14, training avg loss 3.746434, training avg acc 0.298164\n",
      "epoch 14, testing avg loss 6.603992, testing avg acc 0.133580\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:56<00:00,  3.28it/s, accuracy=0.458, cost=2.59]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:04<00:00,  8.36it/s, accuracy=0.113, cost=6.6] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 15, training avg loss 3.688589, training avg acc 0.305162\n",
      "epoch 15, testing avg loss 6.701734, testing avg acc 0.134264\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:18<00:00,  3.57it/s, accuracy=0.473, cost=2.52]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:04<00:00,  8.81it/s, accuracy=0.113, cost=6.63]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 16, training avg loss 3.635814, training avg acc 0.311406\n",
      "epoch 16, testing avg loss 6.761122, testing avg acc 0.134288\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:37<00:00,  3.42it/s, accuracy=0.478, cost=2.53]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:04<00:00,  8.21it/s, accuracy=0.102, cost=6.81]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 17, training avg loss 3.586654, training avg acc 0.317420\n",
      "epoch 17, testing avg loss 6.834680, testing avg acc 0.132595\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:42<00:00,  3.38it/s, accuracy=0.478, cost=2.46]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:04<00:00,  8.51it/s, accuracy=0.14, cost=6.76] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 18, training avg loss 3.543190, training avg acc 0.322967\n",
      "epoch 18, testing avg loss 6.906493, testing avg acc 0.132818\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:19<00:00,  3.56it/s, accuracy=0.512, cost=2.4] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:04<00:00,  8.56it/s, accuracy=0.102, cost=6.89]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 19, training avg loss 3.501456, training avg acc 0.328318\n",
      "epoch 19, testing avg loss 6.967230, testing avg acc 0.131355\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:42<00:00,  3.38it/s, accuracy=0.503, cost=2.36]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:04<00:00,  8.61it/s, accuracy=0.102, cost=6.93]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 20, training avg loss 3.460544, training avg acc 0.333871\n",
      "epoch 20, testing avg loss 7.036694, testing avg acc 0.132445\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "import tqdm\n",
    "\n",
    "for e in range(epoch):\n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(train_X), batch_size), desc = 'minibatch loop')\n",
    "    train_loss, train_acc, test_loss, test_acc = [], [], [], []\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(train_X))\n",
    "        batch_x = pad_sequences(train_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(train_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y}\n",
    "        accuracy, loss, _ = sess.run([model.accuracy,model.cost,model.optimizer],\n",
    "                                    feed_dict = feed)\n",
    "        train_loss.append(loss)\n",
    "        train_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    \n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(test_X), batch_size), desc = 'minibatch loop')\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(test_X))\n",
    "        batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(test_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y,}\n",
    "        accuracy, loss = sess.run([model.accuracy,model.cost],\n",
    "                                    feed_dict = feed)\n",
    "\n",
    "        test_loss.append(loss)\n",
    "        test_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    print('epoch %d, training avg loss %f, training avg acc %f'%(e+1,\n",
    "                                                                 np.mean(train_loss),np.mean(train_acc)))\n",
    "    print('epoch %d, testing avg loss %f, testing avg acc %f'%(e+1,\n",
    "                                                              np.mean(test_loss),np.mean(test_acc)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 40/40 [01:57<00:00,  2.94s/it]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "0.0094467895"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from tensor2tensor.utils import bleu_hook\n",
    "\n",
    "results = []\n",
    "for i in tqdm.tqdm(range(0, len(test_X), batch_size)):\n",
    "    index = min(i + batch_size, len(test_X))\n",
    "    batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "    feed = {model.X: batch_x}\n",
    "    p = sess.run(model.fast_result,feed_dict = feed)[:,0,:]\n",
    "    result = []\n",
    "    for row in p:\n",
    "        result.append([i for i in row if i > 3])\n",
    "    results.extend(result)\n",
    "    \n",
    "rights = []\n",
    "for r in test_Y:\n",
    "    rights.append([i for i in r if i > 3])\n",
    "    \n",
    "bleu_hook.compute_bleu(reference_corpus = rights,\n",
    "                       translation_corpus = results)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
